import hashlib
import os
import time
import uuid

import requests
import urllib.request

from PIL import Image,ImageFile
#防止图片超过178956970 pixels 而报错
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None

#上传图片
def upload_image(item,png_path):
    print("-" * 20, "上传快照", "-" * 20)
    local_time = str(int(time.time()))

    uid = str(uuid.uuid4())
    file = {"file": ("{}".format(png_path.split("all_img_1\\")[1]), open(png_path, 'rb'), "image/png")}

    data = "appid=liyang&time=%s&uuid=%sa9bd8a47c066ca9e9373f4d4ad1d195b" % (local_time, uid)

    url = "http://jianshe.facms.cn/api/v1/file/server-images"
    md = hashlib.md5(data.encode(encoding="utf-8"))  # MD5 : a0541522fbd743537870cb5ee927e508

    headers = {
        # "Content-Type": "images/png",
        "appid": "liyang",
        "uuid": uid,
        "time": local_time,  # 时间戳
        "sign": md.hexdigest()  # 根据data生成的MD5
    }

    response = requests.post(url=url, headers=headers, files=file)
    resp = response.json()

    if resp["message"] == "OK":
        print('上传成功')
        item["kuaizhao_url"] = resp["data"]["url"]
        item["kuaizhao_id"] = resp["data"]["id"]
        # print(item["快照地址"])
    else:
        print("图片上传失败！")
        item["kuaizhao_url"] = ""
        item["kuaizhao_id"] = ""
        print("{}".format(resp["code"]))
        with open("快照问题项目.txt", "a+", encoding="utf-8") as io:
            io.write("{}\n".format(item["项目名称"], ))
    return item

def download_img(item,img_url):

    file_name = str(img_url[-11:-4])
    img_url = img_url
    file_path = 'E:\\all_img'
    img_dir = 'E:\\all_img_1\\'
    img_path = 'E:\\all_img_1\\'+file_name+'.png'
    try:
        # 是否有这个路径
        if not os.path.exists(file_path):
            # 创建路径
            os.makedirs(file_path)

        if not os.path.exists(img_dir):
            # 创建路径
            os.makedirs(img_dir)
            # 获得图片后缀
        file_suffix = os.path.splitext(img_url)[1]
        # 拼接图片名（包含路径）
        filename = '{}{}{}{}'.format(file_path, os.sep, file_name, file_suffix)

        # 下载图片，并保存到文件夹中
        urllib.request.urlretrieve(img_url, filename=filename)
        #压缩图片
        im = Image.open(filename)
        # quality 是设置压缩比
        im.save(img_path, quality=20)
        os.remove(filename)
        res = upload_image(item,img_path)
        #把图片删除
        os.remove(img_path)
    except IOError as e:
        print(e)

        print("IOError")
    except Exception as e:
        print(e)
        print("Exception")

    return item

# i1=dict()
# download_img(i1,'http://rccr.cweun.org/UPFILES/image/20210820/6376505307176542118142672.png')